const fs = require('fs').promises;
const path = require('path');
const { query } = require('./mysql.cjs');

// [DELAY-1] 延时函数 - 测试用，可移除
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function processFiles(event, { inputPath, outputPath, replaceName, dbOption }) {
  try {
    // 获取所有需要处理的文件
    const files = await getAllFiles(inputPath);
    let current = 0;
    const total = files.length;

    // 处理每个文件
    for (const file of files) {
      const relativePath = path.relative(inputPath, file);
      event.sender.send('process-progress', {
        current,
        total,
        currentFile: relativePath
      });

      // 创建新的文件路径（替换文件夹名和文件名中的 copyme）
      // const newRelativePath = relativePath.replace(/copyme/gi, replaceName);
      // 获取'D:/output/inputPath/newRelativePath'的最后文件夹

      // const newFolderPath = path.join(outputPath, inputPath, path.dirname(newRelativePath));
      const newPath = path.join(outputPath, path.basename(inputPath), relativePath).replace(/copyme/gi, replaceName);
      console.log('000001 newPath: ', newPath);

      // 确保目标目录存在
      await fs.mkdir(path.dirname(newPath), { recursive: true });

      try {
        // 读取文件内容
        const content = await fs.readFile(file, 'utf-8');
        
        // 替换文件内容中的所有 copyme，保持原始大小写格式
        const newContent = content.replace(/copyme/gi, match => {
          if (match === match.toLowerCase()) {
            // 把replaceName的首字母小写
            return replaceName.charAt(0).toLowerCase() + replaceName.slice(1);
          } else if (match === 'Copyme') {
            return replaceName.charAt(0).toUpperCase() + replaceName.slice(1);
          }
          return replaceName;
        });
        
        // 写入新文件
        await fs.writeFile(newPath, newContent, 'utf-8');
        
        // [DELAY-2] 文件处理后的延时 - 测试用，可移除
        await delay(500);
      } catch (readError) {
        console.warn(`无法处理文件内容: ${file}`, readError);
        await fs.copyFile(file, newPath);
        // [DELAY-3] 文件复制后的延时 - 测试用，可移除
        await delay(200);
      }

      // 创建表
      // await window.electron.ipcRenderer.invoke('create-table', {
      //   databaseName: dbOption.database,
      //   tableName: replaceName,
      //   columns: ['id INT AUTO_INCREMENT PRIMARY KEY', 'name VARCHAR(255)']
      // });

      // current++;
      // // 更新进度
      // event.sender.send('process-progress', {
      //   current,
      //   total,
      //   currentFile: relativePath
      // });
    }

    const entityPath = path.join(inputPath, '../..', 'entities', 'copyme.entity.ts');
    console.log('000003 entityPath: ', entityPath);

    // 读取entityPath文件内容
    const entityContent = await fs.readFile(entityPath, 'utf-8');
    console.log('000004 entityContent: ', entityContent);

    // 解析 entity 内容，获取表名和字段信息
    const tableNameMatch = entityContent.match(/@Entity\('([^']+)'\)/);
    const tableName = tableNameMatch ? tableNameMatch[1].replace(/copyme/gi, replaceName) : `tb_${replaceName}`;

    // 解析所有的列定义
    const columnRegex = /@(?:PrimaryGeneratedColumn|Column|CreateDateColumn|UpdateDateColumn|DeleteDateColumn)\(([\s\S]*?)\)[^;]*;/g;
    const propertyRegex = /@(?:PrimaryGeneratedColumn|Column|CreateDateColumn|UpdateDateColumn|DeleteDateColumn)/;
    
    const columns = [];
    let match;
    
    while ((match = columnRegex.exec(entityContent)) !== null) {
      const decoratorLine = match[0];
      const options = match[1];
      
      // 获取装饰器类型
      const decoratorMatch = decoratorLine.match(propertyRegex);
      const decoratorType = decoratorMatch ? decoratorMatch[0] : '';
      
      // 解析列配置
      let columnName, columnType, columnComment;
      
      if (options.includes('name:')) {
        const nameMatch = options.match(/name:\s*'([^']+)'/);
        columnName = nameMatch ? nameMatch[1] : null;
      }
      
      if (options.includes('type:')) {
        const typeMatch = options.match(/type:\s*'([^']+)'/);
        columnType = typeMatch ? typeMatch[1] : null;
      }
      
      if (options.includes('comment:')) {
        const commentMatch = options.match(/comment:\s*'([^']+)'/);
        columnComment = commentMatch ? commentMatch[1] : null;
      }
      
      // 根据装饰器类型设置默认值
      switch (decoratorType) {
        case '@PrimaryGeneratedColumn':
          columns.push({
            name: columnName || 'id',
            type: columnType || 'bigint',
            isPrimary: true,
            autoIncrement: true
          });
          break;
        case '@CreateDateColumn':
        case '@UpdateDateColumn':
        case '@DeleteDateColumn':
          columns.push({
            name: columnName,
            type: 'datetime',
            default: 'CURRENT_TIMESTAMP'
          });
          break;
        case '@Column':
          columns.push({
            name: columnName,
            type: columnType === 'simple-json' ? 'json' : (columnType || 'varchar(255)'),
            comment: columnComment
          });
          break;
      }
    }
    
    // 生成建表 SQL
    const createTableSQL = `CREATE TABLE IF NOT EXISTS ${tableName} (
      ${columns.map(col => {
        let definition = `${col.name} ${col.type}`;
        if (col.isPrimary) definition += ' PRIMARY KEY';
        if (col.autoIncrement) definition += ' AUTO_INCREMENT';
        if (col.default) definition += ` DEFAULT ${col.default}`;
        if (col.comment) definition += ` COMMENT '${col.comment}'`;
        return definition;
      }).join(',\n      ')}
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`;
    
    console.log('Generated SQL:', createTableSQL);
    
    console.log('000005 dbOption: ', dbOption);
    // 执行建表 SQL
    if (dbOption && dbOption.database && dbOption.host && dbOption.port && dbOption.username && dbOption.password) {
      await query(null, {
        database: dbOption.database,
        host: dbOption.host,
        port: dbOption.port,
        username: dbOption.username,
        password: dbOption.password,
        sql: createTableSQL
      });
    }

    // [DELAY-4] 处理完成后的延时 - 测试用，可移除
    await delay(300);
    event.sender.send('process-progress', {
      current: total,
      total,
      currentFile: '处理完成'
    });

    return { success: true };
  } catch (error) {
    console.error('处理文件时出错:', error);
    return { success: false, error: error.message };
  }
}

async function getAllFiles(dir) {
  const files = [];
  const entries = await fs.readdir(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      files.push(...await getAllFiles(fullPath));
    } else {
      files.push(fullPath);
    }
  }

  return files;
}

module.exports = { processFiles }; 